package main

import (
	"crypto/x509"
	"fmt"
	"os"

	"github.com/smallstep/truststore"
)

const (
	defaultCertFile = "root.ca.crt"
)

func main() {
	fmt.Println(os.Args)
	if len(os.Args) < 2 {
		fmt.Println("Usage: rcai install/uninstall <path to root.crt>")
		return
	}

	var action = os.Args[1]
	if action != "install" && action != "uninstall" {
		fmt.Println("Usage: rcai install/uninstall <path to root.crt>")
		return
	}

	var certFilePath string
	if len(os.Args) >= 3 {
		certFilePath = os.Args[2]
	} else {
		certFilePath = defaultCertFile
	}
	// 读取根证书pem文件，并转为x509.Certificate类型
	rootCert, err := truststore.ReadCertificate(certFilePath)
	if err != nil {
		fmt.Println("读取证书失败出错")
		fmt.Println(err)
		panic(err)
	}

	if action == "install" {
		err = installRoot(rootCert)
	} else {
		err = uninstallRoot(rootCert)
	}
	if err != nil {
		fmt.Println("操作失败")
		fmt.Println(err)
		panic(err)
	}
	fmt.Printf("%s 操作成功\r\n", action)
}

// installRoot installs this CA's root certificate into the
// local trust store(s) if it is not already trusted. The CA
// must already be provisioned.
func installRoot(rootCert *x509.Certificate) error {
	// avoid password prompt if already trusted
	if trusted(rootCert) {
		fmt.Println("root certificate is already trusted by system")
		return nil
	}

	fmt.Println("installing root certificate (you might be prompted for password)")

	return truststore.Install(rootCert,
		truststore.WithDebug(),
		truststore.WithFirefox(),
		truststore.WithJava(),
	)
}

// uninstallRoot removes this CA's root certificate from the local trust store(s).
func uninstallRoot(rootCert *x509.Certificate) error {
	return truststore.Uninstall(rootCert, truststore.WithDebug(),
		truststore.WithFirefox(),
		truststore.WithJava())
}

func trusted(cert *x509.Certificate) bool {
	chains, err := cert.Verify(x509.VerifyOptions{})
	return len(chains) > 0 && err == nil
}
